import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { CookieService } from 'angular2-cookie/services/cookies.service';

import { Config } from '../share/config';

@Injectable()
export class LoginService {

  constructor(
    private http: Http,
    private _cookieService: CookieService
  ) { }

  /* 获取验证码 */
  getCaptcha(): Observable<any> {
    const url = `${Config.apiRoot}captcha`;
    const options = new RequestOptions({
      withCredentials: true
    });
    return this.http.get(url, options)
      .map(this.extraData)
      .catch(this.handleError);
  }

  /**
   * 登录操作
   * @param loginInfo 登录信息
   * {
   *  name: 'admin', // 用户名
   *  pwd: '123456', // 明文密码
   *  captcha: '10', // 验证码
   *  remember: false // 30天自动登录
   * }
   */
  doLogin(loginInfo) {
    const url = `${Config.apiRoot}user/login`;
    const body = JSON.stringify(loginInfo);
    const headers = new Headers({ 'Content-Type': 'application/json' });

    const options = new RequestOptions({
      headers: headers,
      withCredentials: true
    });
    return this.http.post(url, body, options)
      .map(this.extraData)
      .catch(this.handleError);
  }

  /* 自动登录 */
  doAutoLogin() {
    const url = `${Config.apiRoot}user/autoLogin`;
    const loginInfo = this._cookieService.getObject('login');
    const body = JSON.stringify(loginInfo);
    const headers = new Headers({ 'Content-Type': 'application/json' });

    const options = new RequestOptions({
      headers: headers,
      withCredentials: true
    });
    return this.http.post(url, body, options)
      .map(this.extraData)
      .catch(this.handleError);
  }

  private extraData(res) {
    const body = res.json();
    return body || [];
  }

  /* 登出操作 */
  doLogout(): Observable<any> {
    const name = (<any>this._cookieService.getObject('login')).name;
    const url = `${Config.apiRoot}user/logout?name=${name}`;
    const options = new RequestOptions({
      withCredentials: true
    });
    return this.http.get(url, options)
      .map(this.extraData)
      .catch(this.handleError);
  }

  private handleError(error) {
    const errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : `Server error`;
    console.error(errMsg);

    return Observable.throw(errMsg);
  }
}
